package com.util.cdb.util;

import com.util.cdb.bean.vo.BaseConnectionVO;
import com.util.cdb.enums.DataSourceEnum;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.jdbc.core.JdbcTemplate;

import java.sql.SQLException;

/**
 * @description: 数据源连接池
 * @author: fengfazheng
 * @create: 2021-12-26 15:21
 **/
public class HikariConfigUtil {
    public static HikariDataSource dataSource;

    /**
     * 获取数据源
     */
    public static JdbcTemplate getJdbcTemplate(BaseConnectionVO baseConnectionVO) throws SQLException {

        // 因为dataSource是全局变量、默认初始化值为null
        if (dataSource == null) {
            //初始化HikariConfig
            HikariConfig config = new HikariConfig();
            config.setJdbcUrl(baseConnectionVO.getJdbcUrl());
            config.setDriverClassName(DataSourceEnum.getDbDriver(baseConnectionVO.getDbType()));
            config.setUsername(baseConnectionVO.getUsername());
            config.setPassword(baseConnectionVO.getPassword());
            config.setMinimumIdle(5);
            config.setAutoCommit(true);
            config.setConnectionTimeout(30000);
            //config.s
            // 将config对象传入给HikariDataSource ，返回dataSource
            dataSource = new HikariDataSource(config);
        }
        // 返回dataSource
        return new JdbcTemplate(dataSource);

    }
}
